//
//  LSNewsDetailViewController.m
//  LaSaCivilAffairsDepartment
//
//  Created by 聂志康 on 2019/1/11.
//  Copyright © 2019 wpkj. All rights reserved.
//

#import "LSNewsDetailViewController.h"
#import <WebKit/WebKit.h>
#import "YBImageBrowser.h"
#import "PBProgressView.h"

@interface LSNewsDetailViewController () <WKNavigationDelegate, WKUIDelegate, UIScrollViewDelegate, YBImageBrowserDataSource, UIDocumentInteractionControllerDelegate>//WKScriptMessageHandler
@property (nonatomic, assign) CGFloat titleHeight;
@property (nonatomic, assign) CGFloat imageHeight;
@property (nonatomic, assign) CGFloat attachmentsHeight;
@property (nonatomic, assign) CGFloat webViewContentHeight;
@property (nonatomic, strong) UIScrollView *mainScrollView;
@property (nonatomic, strong) UIView *titleView;
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UILabel *originLabel;
@property (nonatomic, strong) UILabel *releaseDateLabel;
@property (nonatomic, strong) UIView *lineView;
@property (nonatomic, strong) UIImageView *imageView;
@property (nonatomic, strong) WKWebView *webView;
@property (nonatomic, strong) WKWebViewConfiguration *webConfig;
@property (nonatomic, strong) NSArray *attachmentsArray;
@property (nonatomic, copy) NSString *typeImgString;
@property (nonatomic, strong) NSMutableArray *attachmentsProgressesM;
@end

@implementation LSNewsDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"详情";
    self.titleHeight = 80.0f;
    self.imageHeight = 0.0f;
    self.attachmentsHeight = 0.0f;
    self.webViewContentHeight = 0.0f;
    self.view.backgroundColor = UIColor.whiteColor;
    [self.view addSubview:self.mainScrollView];
    UIView *titleView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, self.titleHeight+30+30+10)];
    self.titleView = titleView;
    titleView.backgroundColor = UIColor.whiteColor;
    [self.mainScrollView addSubview:titleView];
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, 0, ScreenWidth-30, self.titleHeight)];
    titleLabel.textColor = NAV_COLOR;
    self.titleLabel = titleLabel;
    titleLabel.font = [UIFont fontWithName:@"SourceHanSansCN-Regular" size:22];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.numberOfLines = 0;
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(15, self.titleHeight-1, ScreenWidth-30, 1)];
    self.lineView = lineView;
    lineView.backgroundColor = NAV_COLOR;
    [self.titleView addSubview:titleLabel];
    [self.titleView addSubview:lineView];
    UILabel *originLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, self.titleHeight, ScreenWidth-30, 30) andText:@"" andTextColor:hexColor(333333) andFont:[UIFont fontWithName:@"SourceHanSansCN-Regular" size:15] andTextAlignment:NSTextAlignmentLeft];
    self.originLabel = originLabel;
    [self.titleView addSubview:originLabel];
    UILabel *releaseDateLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, self.titleHeight+30, ScreenWidth-30, 30) andText:@"" andTextColor:hexColor(333333) andFont:[UIFont fontWithName:@"SourceHanSansCN-Regular" size:15] andTextAlignment:NSTextAlignmentLeft];
    self.releaseDateLabel = releaseDateLabel;
    [self.titleView addSubview:releaseDateLabel];
    [self.titleView addSubview:self.imageView];
    
    
    NSMutableString *jScript = [[NSMutableString alloc] initWithString:@"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta); var imgs = document.getElementsByTagName('img');for (var i in imgs){imgs[i].style.maxWidth='100%';imgs[i].style.height='auto';}"];
    [jScript appendString:@"document.documentElement.style.webkitTouchCallout='none';"];//禁止长按
    [jScript appendString:@"document.documentElement.style.webkitUserSelect='none';"];//禁止选择
    [jScript appendString:@"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta);"];//自适应屏幕宽度
    
    WKUserScript *wkUScript = [[WKUserScript alloc] initWithSource:jScript injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
    
    WKUserContentController *wkUController = [[WKUserContentController alloc] init];
    [wkUController addUserScript:wkUScript];
    WKWebViewConfiguration *wkWebConfig = [[WKWebViewConfiguration alloc] init];
    wkWebConfig.userContentController = wkUController;
    
    WKWebView *webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, self.titleHeight+70, ScreenWidth, ScreenHeight-SafeAreaTopHeight-self.titleHeight-30-30-10) configuration:wkWebConfig];
    webView.scrollView.showsVerticalScrollIndicator = false;
    webView.scrollView.delegate = self;
    webView.scrollView.scrollEnabled = false;
    webView.backgroundColor = [UIColor whiteColor];
    webView.navigationDelegate = self;
    webView.UIDelegate = self;
    self.webView = webView;
    [self.mainScrollView addSubview:webView];
    if (_HtmlString) {
//        [self.webView loadHTMLString:[self reSizeImageWithHTML:self.HtmlString] baseURL:nil];
        [self.webView loadHTMLString:self.HtmlString baseURL:nil];
    }
    [self loadData];
}

- (void)layoutContents {
    self.titleView.frame = CGRectMake(0, 0, ScreenWidth, self.titleHeight+30+30+10);
    self.titleLabel.frame = CGRectMake(15, 0, ScreenWidth-30, self.titleHeight);
    self.lineView.frame = CGRectMake(15, self.titleHeight-1, ScreenWidth-30, 1);
    self.originLabel.frame = CGRectMake(15, self.titleHeight, ScreenWidth-30, 30);
    self.releaseDateLabel.frame = CGRectMake(15, self.titleHeight+30, ScreenWidth-30, 30);
}

- (NSString *)reSizeImageWithHTML:(NSString *)html {
    return [NSString stringWithFormat:@"<meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0'><meta name='apple-mobile-web-app-capable' content='yes'><meta name='apple-mobile-web-app-status-bar-style' content='black'><meta name='format-detection' content='telephone=no'><style type='text/css'>img{width:%@} p{font-size:14px}</style>%@",@"100%",html];
}

- (WKWebViewConfiguration *)webConfig {
    if (!_webConfig) {
        _webConfig = [WKWebViewConfiguration new];
        WKUserContentController *userController = [WKUserContentController new];
        NSMutableString *javascript = [NSMutableString string];
        [javascript appendString:@"document.documentElement.style.webkitTouchCallout='none';"];//禁止长按
        [javascript appendString:@"document.documentElement.style.webkitUserSelect='none';"];//禁止选择
//        [javascript appendString:@" $('meta[name=description]').remove(); $('head').append( '<meta name=\"viewport\" content=\"width=device-width, initial-scale=1,user-scalable=no\">' );"];
        WKUserScript *script = [[WKUserScript alloc] initWithSource:javascript injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:NO];
        [userController addUserScript:script];
//        [userController addScriptMessageHandler:self name:@"openInfo"];
        _webConfig.userContentController = userController;
    }
    return _webConfig;
}

- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView{
    return nil;
}

//// WKNavigationDelegate 页面加载完成之后调用
//- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation {

//    修改字体颜色  #9098b8
//    [webView evaluateJavaScript:@"document.getElementsByTagName('body')[0].style.webkitTextFillColor= '#9098b8'" completionHandler:nil];
//    使得webView里面的图片自适应屏幕的宽度
//    [webView evaluateJavaScript:@"document.body.offsetHeight;" completionHandler:^(id _Nullable any, NSError * _Nullable error) {
//        NSString *heightStr = [NSString stringWithFormat:@"%@",any];
//        NSLog(@"heightStr---%@",heightStr);
//        webView.scrollView.contentSize = CGSizeMake(ScreenWidth-1, heightStr.floatValue);// CGRectMake(0, 0, ScreenWidth-1, heightStr.floatValue);
//                //下面的wkWeb已经可以完美展示了，不过我的界面是自定义的
//                wk_web.frame = CGRectMake(0, _headerImage.frame.origin.y + ScreenW, ScreenW, heightStr.floatValue);
//                //所以，我的界面最底部是scrollView，其中包含：其他的视图 + wk_web，注意：100 + ScreenW 就是其他的视图，举个简单的例子而已。
//                _mScroll_ViewHHH.constant = 100 + ScreenW + heightStr.floatValue;
//    }];
//    修改字体大小 300%
//        [ webView evaluateJavaScript:@"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '220%'" completionHandler:nil];
//}

- (void)loadData {
    [NetworkUtils requestNOHandleWithMethod:@"POST" URL:NewsDetail param:@{@"token":[ValidateUtils validateNull:[UserInfoModel sharedInstance].token],@"id":self.newsDetailID} completionHandler:^(id responseObject, NSError *connectionError) {
        if (!connectionError) {
            NSLog(@"responseObject---%@",responseObject);
            NSDictionary *dataDict = [responseObject objectForKey:@"data"];
            if (dataDict && dataDict.count > 0) {
                self.titleLabel.text = [ValidateUtils validateNull:dataDict[@"title"]];
                CGRect TitleRect = [[ValidateUtils validateNull:dataDict[@"title"]] boundingRectWithSize:CGSizeMake(ScreenWidth-30, 0) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : [UIFont fontWithName:@"SourceHanSansCN-Regular" size:22]} context:nil];
                self.titleHeight = TitleRect.size.height+10;
                [self layoutContents];
                self.originLabel.text = [NSString stringWithFormat:@"发布机构：%@",[ValidateUtils validateNull:dataDict[@"author"]]];
                self.releaseDateLabel.text = [NSString stringWithFormat:@"发布时间：%@",[self timeStampToDate:[ValidateUtils validateNull:dataDict[@"releaseDate"]]]];
                self.attachmentsArray = dataDict[@"attachments"];
                self.typeImgString = dataDict[@"typeImg"];
                if (![[ValidateUtils validateNull:self.typeImgString] isEqualToString:@""]) {
                    [self arrangeImageView];
                }
                [self.webView loadHTMLString:dataDict[@"txt"] baseURL:nil];
            } else {
                [MBProgressHUD showTipMessageInWindow:[ValidateUtils validateNull:[responseObject objectForKey:@"message"]]];
            }
        } else {
            [MBProgressHUD showTipMessageInWindow:connectionError.localizedDescription];
        }
    }];
}

- (NSString *)timeStampToDate:(NSString *)timeStampString {
    // iOS 生成的时间戳是10位
    if (![[ValidateUtils validateNull:timeStampString] isEqualToString:@""] && !([ValidateUtils validateNull:timeStampString].integerValue == 0)) {
        NSTimeInterval interval    =[timeStampString doubleValue] / 1000.0;
        NSDate *date               = [NSDate dateWithTimeIntervalSince1970:interval];
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"yyyy-MM-dd"];
        return [formatter stringFromDate: date];
    }
    return @"";
}

- (void)arrangeImageView {
    self.imageHeight = 310.0f;
    self.imageView.frame = CGRectMake((ScreenWidth-(self.imageHeight-10))/2, self.titleHeight+30+30+10, self.imageHeight-10, self.imageHeight-10);
    [self.imageView sd_setImageWithURL:[NSURL URLWithString:self.typeImgString] placeholderImage:PlaceholderImage options:SDWebImageRefreshCached completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
        self.imageView.userInteractionEnabled = true;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(imageViewClicked)];
        [self.imageView addGestureRecognizer:tap];
    }];
}

- (void)imageViewClicked {
    //创建图片浏览器（注意：更多功能请看 YBImageBrowser.h 文件或者 github readme）
    YBImageBrowser *browser = [YBImageBrowser new];
//    browser.dataArray = tempArr;
//    browser.currentIndex = 1;
    browser.dataSource = self;
    
    //展示
    [browser show];
}

/**
 返回点击的那个 UIImageView（用于做 YBImageBrowserAnimationMove 类型动效）
 
 @param imageBrowser 当前图片浏览器
 @return 点击的图片视图
 */
- (UIImageView * _Nullable)imageViewOfTouchForImageBrowser:(YBImageBrowser *)imageBrowser {
    return self.imageView;
}

/**
 配置图片的数量
 
 @param imageBrowser 当前图片浏览器
 @return 图片数量
 */
- (NSInteger)numberInYBImageBrowser:(YBImageBrowser *)imageBrowser {
    return 1;
}

/**
 返回当前 index 图片对应的数据模型
 
 @param imageBrowser 当前图片浏览器
 @param index 当前下标
 @return 数据模型
 */
- (YBImageBrowserModel *)yBImageBrowser:(YBImageBrowser *)imageBrowser modelForCellAtIndex:(NSInteger)index {
    YBImageBrowserModel *model = [YBImageBrowserModel new];
    [model setImage:self.imageView.image];
    model.sourceImageView = self.imageView;
    return model;
}

// WKNavigationDelegate 页面加载完成之后调用
- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation {
    //修改字体大小 300%
//    [webView evaluateJavaScript:@"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '50%'" completionHandler:nil];
    // 禁止放大缩小
    NSString *injectionJSString = @"var script = document.createElement('meta');"
    "script.name = 'viewport';"
    "script.content=\"width=device-width, initial-scale=1.0,maximum-scale=1.0, minimum-scale=1.0, user-scalable=no\";"
    "document.getElementsByTagName('head')[0].appendChild(script);";
    WS
    [webView evaluateJavaScript:injectionJSString completionHandler:nil];
    [webView evaluateJavaScript:@"document.body.offsetHeight;" completionHandler:^(id _Nullable any, NSError * _Nullable error) {
        NSString *heightStr = [NSString stringWithFormat:@"%@",any];
        NSLog(@"heightStr---%@",heightStr);
        self.webViewContentHeight = heightStr.floatValue;
        webView.frame = CGRectMake(0, self.titleHeight+30+30+self.imageHeight, ScreenWidth-1, heightStr.floatValue+SafeAreaTopHeight);
        if (self.attachmentsArray.count > 0) {
            weakSelf.attachmentsHeight = 40*self.attachmentsArray.count;
            [weakSelf arrangeFiles];
        }
        weakSelf.mainScrollView.contentSize = CGSizeMake(ScreenWidth-1, heightStr.floatValue+SafeAreaTopHeight+self.titleHeight+30+30+self.imageHeight+self.attachmentsHeight);
//        //下面的wkWeb已经可以完美展示了，不过我的界面是自定义的
//        wk_web.frame = CGRectMake(0, _headerImage.frame.origin.y + ScreenW, ScreenW, heightStr.floatValue);
//        //所以，我的界面最底部是scrollView，其中包含：其他的视图 + wk_web，注意：100 + ScreenW 就是其他的视图，举个简单的例子而已。
//        _mScroll_ViewHHH.constant = 100 + ScreenW + heightStr.floatValue;
    }];
    [webView.scrollView setContentOffset:CGPointZero animated:false];
}

- (void)arrangeFiles {
    for (int i = 0; i < self.attachmentsArray.count; i++) {
        NSDictionary *dict = self.attachmentsArray[i];
        UILabel *tipLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, self.webViewContentHeight+self.imageHeight+self.titleHeight+30+30+40*i+SafeAreaTopHeight, 81, 40) andText:@"附件下载：" andTextColor:hexColor(333333) andFont:[UIFont fontWithName:@"SourceHanSansCN-Regular" size:16] andTextAlignment:NSTextAlignmentLeft];
        UILabel *underlineLabel = [[UILabel alloc] initWithFrame:(CGRectMake(90, self.webViewContentHeight+self.imageHeight+self.titleHeight+30+30+40*i+SafeAreaTopHeight, ScreenWidth-90-10, 40))];
        underlineLabel.numberOfLines = 2;
        NSString *textStr = [ValidateUtils validateNull:dict[@"name"]];
        // 下划线
        NSDictionary *attribtDic = @{NSUnderlineStyleAttributeName: [NSNumber numberWithInteger:NSUnderlineStyleSingle]};
        NSMutableAttributedString *attribtStr = [[NSMutableAttributedString alloc]initWithString:textStr attributes:attribtDic];
        //赋值
        underlineLabel.attributedText = attribtStr;
        underlineLabel.tag = TagFoundation+i;
        underlineLabel.userInteractionEnabled = true;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(underlineLabelTapped:)];
        [underlineLabel addGestureRecognizer:tap];
        [self.mainScrollView addSubview:tipLabel];
        [self.mainScrollView addSubview:underlineLabel];
        PBProgressView *progressView = [[PBProgressView alloc] initWithFrame:CGRectMake(90, self.webViewContentHeight+self.imageHeight+self.titleHeight+30+30+40*i+SafeAreaTopHeight+18, ScreenWidth-90-10, 4) borderColor:NAV_COLOR contentColor:NAV_COLOR];
        progressView.progress = 0.0f;
        progressView.alpha = 0.0f;
        [self.mainScrollView addSubview:progressView];
        [self.attachmentsProgressesM addObject:progressView];
    }
}

- (void)underlineLabelTapped:(UITapGestureRecognizer *)tap {
    UILabel *underlineLabel = (UILabel *)tap.view;
    NSInteger tag = underlineLabel.tag-TagFoundation;
    NSDictionary *dict = self.attachmentsArray[tag];
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths lastObject];
    NSLog(@"app_home_doc: %@",documentsDirectory);
    
    NSString *docPath = [ValidateUtils validateNull:dict[@"name"]];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *filePath = [documentsDirectory stringByAppendingPathComponent:docPath]; //docPath为文件名
    
    if ([fileManager fileExistsAtPath:filePath]) {
        //文件已经存在,直接打开
        UIAlertController * alertController = [UIAlertController alertControllerWithTitle:@"是否打开文件" message:nil preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction * cancelAction  =[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        
        [alertController addAction:cancelAction];
        
        [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
            [self openDocxWithPath:filePath];
        }]];
        
        [alertController.actions setValue:[UIColor colorWithHexString:@"3998ef"] forKey:@"_titleTextColor"];
        [self presentViewController:alertController animated:YES completion:nil];
        
    }else {
        //文件不存在,要下载
        UIAlertController * alertController = [UIAlertController alertControllerWithTitle:@"是否下载并打开文件" message:nil preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction * cancelAction  =[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        
        [alertController addAction:cancelAction];
        
        [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
            underlineLabel.hidden = true;
            PBProgressView *progressView = self.attachmentsProgressesM[tag];
            progressView.alpha = 1.0f;
            [self downloadDocxWithURL:[ValidateUtils validateNull:dict[@"path"]] docPath:documentsDirectory fileName:docPath tag:tag forLabel:underlineLabel];
        }]];
        
        [alertController.actions setValue:[UIColor colorWithHexString:@"3998ef"] forKey:@"_titleTextColor"];
        [self presentViewController:alertController animated:YES completion:nil];
        
    }
}

- (void)downloadDocxWithURL:(NSString *)url docPath:(NSString *)path fileName:(NSString *)fileName tag:(NSInteger)tag forLabel:(UILabel *)underlineLabel {
    PBProgressView *progressView = self.attachmentsProgressesM[tag];
    NSString * URLString = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    [NetworkUtils downloadFileWithURL:URLString filePath:[NSString stringWithFormat:@"%@/%@",path,fileName] progress:^(NSProgress *downloadProgress) {
        progressView.progress = downloadProgress.fractionCompleted;
    } completionHandler:^(id responseObject, NSError *connectionError) {
        underlineLabel.hidden = false;
        progressView.alpha = 0.0f;
        if (!connectionError) {
            [MBProgressHUD showTipMessageInWindow:@"下载完成"];
            [self openDocxWithPath:[NSString stringWithFormat:@"%@/%@",path,fileName]];
        } else {
            [MBProgressHUD showTipMessageInWindow:connectionError.localizedDescription];
        }
    }];
}

-(void)openDocxWithPath:(NSString *)filePath {
    UIDocumentInteractionController *doc= [UIDocumentInteractionController interactionControllerWithURL:[NSURL fileURLWithPath:filePath]];
    doc.delegate = self;
    if ([filePath hasSuffix:@"png"] || [filePath hasSuffix:@"PNG"] || [filePath hasSuffix:@"jpg"] || [filePath hasSuffix:@"JPG"] || [filePath hasSuffix:@"jpeg"] || [filePath hasSuffix:@"gif"] || [filePath hasSuffix:@"GIF"]) {
        [doc presentPreviewAnimated:YES];
    } else {
        [doc presentOpenInMenuFromRect:CGRectZero inView:self.view animated:YES];
    }
}

#pragma mark - UIDocumentInteractionControllerDelegate
//必须实现的代理方法 预览窗口以模式窗口的形式显示，因此需要在该方法中返回一个view controller ，作为预览窗口的父窗口。如果你不实现该方法，或者在该方法中返回 nil，或者你返回的 view controller 无法呈现模式窗口，则该预览窗口不会显示。
- (UIViewController *)documentInteractionControllerViewControllerForPreview:(UIDocumentInteractionController *)controller{
    return self;
}

- (UIView*)documentInteractionControllerViewForPreview:(UIDocumentInteractionController*)controller {
    return self.view;
}

- (CGRect)documentInteractionControllerRectForPreview:(UIDocumentInteractionController*)controller {
    return CGRectMake(0, 30, ScreenWidth, ScreenHeight-SafeAreaTopHeight-30);
}

- (UIScrollView *)mainScrollView {
    if (!_mainScrollView) {
        _mainScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight-SafeAreaTopHeight)];
        _mainScrollView.contentSize = CGSizeMake(ScreenWidth, ScreenHeight-SafeAreaTopHeight);
        _mainScrollView.delegate = self;
    }
    return _mainScrollView;
}

- (UIImageView *)imageView {
    if (!_imageView) {
        _imageView = [[UIImageView alloc] initWithFrame:CGRectMake((ScreenWidth-300)/2, 90, 300, self.imageHeight)];
        _imageView.contentMode = UIViewContentModeScaleAspectFill;
        _imageView.layer.masksToBounds = true;
    }
    return _imageView;
}

- (NSMutableArray *)attachmentsProgressesM {
    if (!_attachmentsProgressesM) {
        _attachmentsProgressesM = [[NSMutableArray alloc] init];
    }
    return _attachmentsProgressesM;
}

@end
